const app = getApp();
const userApi = require('../../api/user.js');

Page({
  data: {
    profileForm: {
      nickname: '',
      gender: '',
      address: '',
      intro: '',
    },
    genderOptions: [
      { label: '男', value: '男' },
      { label: '女', value: '女' },
    ],
    genderIndex: 0,
  },

  onLoad() {
    this.loadData();
  },

  async loadData() {
      const res = await userApi.getUser();
      console.log('个人基本资料:',res);
      const userData = res.data; 
      this.setData({
        profileForm: {
          nickname: userData.nickname,
          gender: userData.gender,
          address: userData.address,
          intro: userData.intro,
        },
        genderIndex: this.data.genderOptions.findIndex(item => item.value === userData.gender),
      });
  },

  handleNicknameInput(e) {
    this.setData({
      'profileForm.nickname': e.detail.value,
    });
  },

  handleGenderChange(e) {
    const index = e.detail.value;
    this.setData({
      genderIndex: index,
      'profileForm.gender': this.data.genderOptions[index].value,
    });
  },

  handleAddressInput(e) {
    this.setData({
      'profileForm.address': e.detail.value,
    });
  },

  handleIntroInput(e) {
    this.setData({
      'profileForm.intro': e.detail.value,
    });
  },

  async setUser() {
      const res = await userApi.setUser(this.data.profileForm);
      console.log('修改成功',res);
      if (res.code === 200) {
        wx.showToast({ title: res.msg || '保存成功' });
        setTimeout(() => {
          wx.navigateBack({ delta: 1 });
        }, 1500);
      } else {
        wx.showToast({ title: res.msg || '保存失败', icon: 'none' });
      }
  },
  handleBack() {
    wx.navigateBack({ delta: 1 });
  },
});